import express from "express";
import { Database } from "../model/database";
import { vaild, sign } from "../middleware/jwt";
import { AdminData } from "../model/database";
import crypto from "crypto";
import reptile from "../middleware/reptile";
import { queryPara } from "../model/database";
import { InterviewDetailsData } from "../model/database";
import mail from "../middleware/mail"

export default function (app: express.Application, db: Database) {

    app.post("/api/pc/begin-interview", (req: any, res: any) => {
        const token: any = typeof req.header("token") === "string" ? req.header("token") : "";
        vaild(token).then((data: any) => {
            let id = req.body.id;
            db.queryStuInformByID(id).then((value: any) => {
                if (value[0].state === 100) {
                    db.upadateStuState(id, 201);
                    let resMsg: string = JSON.stringify({
                        status: 0,
                        msg: "OK"
                    })
                    res.send(resMsg);
                    res.end();
                } else if (value[0].state > 200 && value[0].state < 299) {
                    let resMsg: string = JSON.stringify({
                        status: 0,
                        msg: "OK"
                    })
                    res.send(resMsg);
                    res.end();
                } else {
                    db.upadateStuState(id, value[0].state % 100 + 201);
                    let resMsg: string = JSON.stringify({
                        status: 0,
                        msg: "OK"
                    })
                    res.send(resMsg);
                    res.end();
                }
            })
        }).catch((err) => {
            let resMsg: string = JSON.stringify({
                status: 3,
                msg: err
            });
            res.send(resMsg);
            res.end();
        })
    });

    let subject1: string = "验证";
    let subject2: string = "面试进度通知";
    let text1: string = "点击链接以验证";
    let text2: string = "，恭喜你通过了第";
    let text3: string = "轮面试，请做好准备参加下一轮面试，祝你成功";
    let text4: string = ",很遗憾，你没有通过第";
    let text5: string = "轮面试，希望你在接下来的学习中再接再厉，找准方向，迎接美好的未来";


    let ad: AdminData = {
        id: "",
        name: "",
        group: 0,
        password: "",
        state: 0
    };
    app.post("/api/pc/register", (req: any, res: any) => {
        try {
            if (!req.body.id) {
                req.body.id = {};
            }
            ad.id = req.body.id;
            ad.name = req.body.name;
            ad.password = req.body.password;
            ad.group = req.body.group;
            ad.state = 0;
            let md5 = crypto.createHash("md5");
            let md5Sum = md5.update(ad.password);
            let result = md5Sum.digest("hex");
            let identify: string;
            sign("3G" + Math.random()).then((data: any) => {
                identify = data;
                return new Promise((resolve, reject) => {
                    resolve("ok");
                })
            }).then(() => {
                return db.queryAdminInformByID(ad.id);
            }).then((data: any) => {
                if (!data.length) {
                    return reptile(ad.id, ad.password);
                } else {
                    let resMsg: string = JSON.stringify({
                        status: 2,
                        msg: "exsited"
                    });
                    res.send(resMsg);
                    res.end();

                    return new Promise((reject) => {
                        reject("err");
                    })
                }
            }).then((value: any) => {
                if (!value.tips && value.state === 0) {
                    ad.password = result;
                    db.insertToAdmin(ad);
                    switch (ad.group) {
                        case 1:
                            mail('1290504514@qq.com', subject1, text1 + ad.name + "的注册请求" + "http://121.4.127.126:3000/api/pc/is-pass-register?username=" + ad.id);
                            break;
                        case 2:
                            mail('1223176327@qq.com', subject1, text1 + ad.name + "的注册请求" + "http://121.4.127.126:3000/api/pc/is-pass-register?username=" + ad.id);
                            break;
                        case 3:
                            mail('2101297547@qq.com', subject1, text1 + ad.name + "的注册请求" + "http://121.4.127.126:3000/api/pc/is-pass-register?username=" + ad.id);
                            break;
                        case 4:
                            mail('494478066@qq.com', subject1, text1 + ad.name + "的注册请求" + "http://121.4.127.126:3000/api/pc/is-pass-register?username=" + ad.id);
                            break;
                        // default :
                        //     mail('1242598374@qq.com', subject1, text1 + ad.name + "的注册请求" + "http://121.4.127.126:3000/api/pc/is-pass-register?username=" + ad.id);
                    }
                    let resMsg: string = JSON.stringify({
                        status: 0,
                        msg: "ok"
                    });
                    res.send(resMsg);
                    res.end();
                } else if (value.state === 0) {
                    let resMsg: string = JSON.stringify({
                        status: 2,
                        msg: value.tips
                    });
                    res.send(resMsg);
                    res.end();
                } else {
                    let resMsg: string = JSON.stringify({
                        status: 3,
                        msg: value.errMsg,
                    });
                    res.send(resMsg);
                    res.end();
                }
            })
        } catch (err) {
            let resMsg: string = JSON.stringify({
                status: 3,
                msg: err
            });
            res.send(resMsg);
            res.end();
        }
    });

    app.get("/api/pc/is-pass-register", (req: any, res: any) => {
        try {
            let id = req.query.username;
            db.upadateAdmState(id, 1).then((data: any) => {

                let resMsg: string = "已通过申请";
                res.send(resMsg);
                res.end();
            })
        } catch (err) {
            let resMsg: string = "失败";

            res.send(resMsg);
            res.end();
        }
    });

    app.post("/api/pc/login", (req: any, res: any) => {

        try {
            let id = req.body.id;
            let password = req.body.password;
            let md5 = crypto.createHash("md5");
            let md5Sum = md5.update(password);
            let HashedPW = md5Sum.digest("hex");


            db.queryAdminInformByID(id).then((data: any) => {

                if (data.length) {
                    if (data[0].state === 0) {
                        let resMsg: string = JSON.stringify({
                            status: 2,
                            msg: "注册尚未被通过",
                            result: {},
                        });
                        res.send(resMsg);
                        res.end();
                    }
                    if (data[0].password === HashedPW) {
                        let resMsg: string = JSON.stringify({
                            status: 0,
                            msg: "OK",
                            result: {
                                group: data[0].group,
                                name: data[0].name,
                            },

                        });

                        sign(id).then((data: any) => {
                            res.setHeader("token", data);
                            res.send(resMsg);
                            res.end();
                        })

                    } else {
                        let resMsg: string = JSON.stringify({
                            status: 2,
                            msg: "wrong",
                            result: {},

                        });
                        res.send(resMsg);
                        res.end();
                    }
                } else {
                    let resMsg: string = JSON.stringify({
                        status: 2,
                        msg: "学号或密码不正确",
                    });
                    res.send(resMsg);
                    res.end();
                }
            });
        } catch (err) {
            let resMsg: string = JSON.stringify({
                status: 3,
                msg: err,
            });
            res.send(resMsg);
            res.end();
        }
    });

    class evaluInfo {
        point !: number;
        text !: string;
        id !: string;
    }
    app.get("/api/pc/get-signle-applicant", (req: any, res: any) => {
        const token: any = typeof req.header("token") === "string" ? req.header("token") : "";
        let arr1 = new Array();
        let arr2 = new Array();
        let interview = new Array(2);
        vaild(token).then((data: any) => {
            let id = req.query.id;
            let j: number = 0;
            let k: number = 0;
            db.queryStuInterviewByID(id).then((interviewRes: any) => {
                for (let i = 0; i < interviewRes.length; i++) {
                    db.queryAdminInformByID(interviewRes[i].judge).then((intRes: any) => {
                        if (intRes.length) {
                            let ei: evaluInfo = {
                                point: interviewRes[i].score,
                                text: interviewRes[i].evalu,
                                id: intRes[0].name
                            };
                            if (interviewRes[i].state % 100 == 1) {
                                arr1[j] = ei;
                                j++;
                            } else if (interviewRes[i].state % 100 == 2) {
                                arr2[k] = ei;
                                k++;
                            }
                        }
                        interview[0] = arr1;
                        interview[1] = arr2;
                    })
                }
            }).then(() => {
                return db.queryStuInformByID(id);
            }).then((value: any) => {
                if (value.length) {
                    value = value[0];
                    let resMsg: string = JSON.stringify({
                        status: 0,
                        msg: "",
                        result: {
                            name: value.name,
                            class: value.class,
                            group: value.group,
                            state: value.state,
                            time: value.time,
                            qq: value.qq,
                            tel: value.tel,
                            why: value.why,
                            hobby: value.hobby,
                            firstscore: value.firstscore,
                            secondscore: value.secondscore,
                            thirdscore: value.thirdscore,
                            fourthscore: value.fourthscore,
                            interview: interview,
                        }
                    });
                    res.send(resMsg);
                    res.end();
                } else {
                    let resMsg: string = JSON.stringify({
                        status: 2,
                        msg: "不存在"
                    });
                    res.send(resMsg);
                    res.end();
                }
            })
        }).catch((err) => {
            let resMsg: string = JSON.stringify({
                status: 3,
                msg: err
            });
            res.send(resMsg);
            res.end();
        })
    });

    let QP: queryPara = {
        group: [],
        status: 0,
        time: [],
    };

    app.post("/api/pc/get-applicant-inform", (req: any, res: any) => {
        try {
            let page = req.body.page;
            QP.group = req.body.group;
            QP.status = req.body.status;
            let num = req.body.num;
            QP.time = req.body.time;
            if (!num) {
                num = 20;
            }
            if (!QP.group || !QP.group.length) {
                QP.group = [1, 2, 3, 4];
            }
            if (!QP.time) {
                QP.time = undefined;
            }
            db.queryStus(QP, page, num).then((value: any) => {
                if (value.resData.length) {

                    let resMsg: string = JSON.stringify({
                        status: 0,
                        msg: "success",
                        result: value.resData,
                        sum: value.sum,

                    });
                    res.send(resMsg);
                    res.end();
                } else {
                    let resMsg: string = JSON.stringify({
                        status: 2,
                        msg: "不存在"
                    });
                    res.send(resMsg);
                    res.end();
                }
            })
        } catch (err) {
            let resMsg: string = JSON.stringify({
                status: 3,
                msg: err
            });
            res.send(resMsg);
            res.end();
        }
    });

    let IDD: InterviewDetailsData = {
        judge: "",
        stu_id: "",
        score: 0,
        evalu: undefined,
        state: 0
    };

    app.post("/api/pc/evaluate-applicant", (req: any, res: any) => {
        const token: any = typeof req.header("token") === "string" ? req.header("token") : "";
        db.queryStuInformByID(req.body.id).then((value: any) => {
            IDD.state = value[0].state;
            return new Promise((resolve, reject) => {
                if (value[0].state < 200 || value[0].state > 300) {
                    reject("无权限进行此操作");

                } else {
                    resolve("ok");
                }
            })
        }).then(() => {
            return vaild(token);
        }).then((data: any) => {
            IDD.stu_id = req.body.id;
            IDD.score = req.body.point;
            IDD.evalu = req.body.text;
            IDD.judge = data.id;
            return db.insertTointerviewDetails(IDD)
        }).then(() => {

            return db.queryStuInterviewByID(IDD.stu_id)
        }).then((data: any) => {
            if (data.length) {
                let score: number = 0;
                for (let i = 0; i < data.length; i++) {
                    score = score + data[i].score;
                }
                score = score / data.length;
                return db.updateStuScore(IDD.stu_id, score);
            } else {
                return db.updateStuScore(IDD.stu_id, IDD.score);
            }
        }).then(() => {
            let resMsg: string = JSON.stringify({
                status: 0,
                msg: "success"
            });
            res.send(resMsg);
            res.end();
        }).catch((err) => {
            let resMsg: string = JSON.stringify({
                status: 3,
                msg: err
            });
            res.send(resMsg);
            res.end();
        })
    });

    app.post("/api/pc/is-pass", (req: any, res: any) => {
        try {
            new Promise((resolve, reject) => {
                (async () => {
                    for (let i = 0; i < req.body.id.length; i++) {
                        await db.queryStuInformByID(req.body.id[i]).then((data: any) => {
                            data = data[0];
                            if (data.state > 199 && data.state < 299) {
                                if (req.body.isPass) {
                                    
                                    data.state += 100;
                                    mail(data.qq, subject2, data.name + text2 + data.state % 100 + text3);
                                   
                                    
                                } else {
                                    mail(data.qq, subject2, data.name + text4 + data.state % 100 + text5);
                                    data.state += 200;
                                }
                                db.upadateStuState(req.body.id[i], data.state);
                                
                            } else {
                                let resMsg: string = JSON.stringify({
                                    status: 3,
                                    msg: "无权限进行此操作",
                                    result: false
                                });
                                res.send(resMsg);
                                res.end();
                            }
                        });
                        if (i === req.body.id.length - 1) {
                            resolve("yes");
                        }

                    }
                })()
            }).then(() => {
                let resMsg: string = JSON.stringify({
                    status: 0,
                    msg: "success",
                    result: true
                });
                res.send(resMsg);
                res.end();
            })
        }
        catch (err) {
            let resMsg: string = JSON.stringify({
                status: 3,
                msg: err
            });
            res.send(resMsg);
            res.end();
        }
    })

}
